<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .wrapper {
        width: 100vw;
        height: 100vh;
        overflow: auto;
      }
      .content {
        height: 2000px;
      }
      #box {
        width: 100px;
        height: 100px;
        background: red;
      }
    </style>
  </head>
  <body>
    <div class="wrapper">
      <div class="content"></div>
      <div id="box" data-id="1"></div>
    </div>
    <script>
      // 选择需要观察变动的节点
      const targetNode = document.getElementById("box");
      const wrapper = document.querySelector(".wrapper");
      targetNode.onclick = function () {
        targetNode.style.background = "green";
        targetNode.dataset.id = 12;
        console.log("targetNode:", targetNode);
      };

      // 观察器的配置（需要观察什么变动）
      const config = { attributes: true, childList: true, subtree: true };

      // 当观察到变动时执行的回调函数
      const callback = function (mutationsList, observer) {
        console.log("observer:", mutationsList, observer);
        // Use traditional 'for loops' for IE 11
        for (let mutation of mutationsList) {
          if (mutation.type === "childList") {
            console.log("A child node has been added or removed.");
          } else if (mutation.type === "attributes") {
            console.log(
              "The " + mutation.attributeName + " attribute was modified."
            );
          }
        }
      };
      // 创建一个观察器实例并传入回调函数
      const observer = new MutationObserver(callback);
      // console.log("observer:", observer);
      // 以上述配置开始观察目标节点
      observer.observe(targetNode, config);

      // 之后，可停止观察
      // observer.disconnect();
    </script>
  </body>
</html>
